package com.crpc.core.serialize.impl;

import com.crpc.common.crpcEnum.CrpcExceptionEnums;
import com.crpc.common.exception.CrpcException;
import com.crpc.core.serialize.Serializer;
import lombok.extern.slf4j.Slf4j;

import java.io.*;

/**
 * @author wzy
 * @version 1.0
 * @description:
 * @date 2023/9/29 15:16
 */
@Slf4j
public class JDKSerializer implements Serializer {
    public JDKSerializer() {
    }

    @Override
    public byte[] serialize(Object object) {
        if (object == null) {
            return null;
        }
        try (
                ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
                ObjectOutputStream outputStream = new ObjectOutputStream(byteArrayOutputStream)
        ) {
            outputStream.writeObject(object);
            log.info("===============jdk序列化完成===============");
            return byteArrayOutputStream.toByteArray();
        } catch (IOException e) {
            log.error("序列化对象：{}，失败原因：{}", object, e.getMessage());
            e.printStackTrace();
            throw new CrpcException(CrpcExceptionEnums.Serialize_ERROR);
        }
    }

    @Override
    public <T> T deserialize(byte[] bytes, Class<T> clazz) {
        if (bytes == null || clazz == null) {
            return null;
        }
        try (
                ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(bytes);
                ObjectInputStream inputStream = new ObjectInputStream(byteArrayInputStream)
        ) {
            log.info("===============jdk反序列化完成===============");
            return (T) inputStream.readObject();

        } catch (Exception e) {
            log.error("反序列化对象：{}，失败原因：{}", bytes, e.getMessage());
            e.printStackTrace();
            throw new CrpcException(CrpcExceptionEnums.Serialize_ERROR);
        }
    }
}
